/**
 * 加载之前打开的tab页
 * @author rainliang@qiyi.com
 */


(function($){

	$.extend({
		NavTabHistory: {
            defaults : {
                tabId:'default_tab',
                title:'default_tab',
                url:'',
                fresh:false,
                external:true
            },
            saveTab:function(tabid, title, url,reloadFlag, fresh, external) { //将tab存到cookie
                if(!this.navtabSaveFlag)return ;
                if(this.isSaved(tabid)>-1)return ; //已经保存，直接返回
                var data = {
                    tabId:tabid,
                    title:title,
                    url:url,
                    fresh:fresh,
                    external:external,
                    reloadFlag:reloadFlag,
                    extend:'extend'
                };
                var option = $.extend(defaults, data);
                if($.NavTabHistory){
                    $.NavTabHistory.addHistory(option);
                }
            },
            removeTab:function(tabid){  //从cookie移除tab
                var _index=this.isSaved(tabid);
                if(_index>-1&&$.NavTabHistory){
                    var data = $.NavTabHistory.loadHistory();
                    var index=this._getHistoryIndex(data,tabid);
                    if(index>=0){
                        data.splice(index,1);
                        jQuery.cookie(this.navTabKey,data.join(this.navTabSplitStr),{expires: 7});
                    }
                    this.navTabIds.splice(_index,1);
                }
            },
            openTabFromCookie:function() {  //登录后 打开上次未关闭的tab
                $.NavTabHistory.navtabSaveFlag=false;
                var data = $.NavTabHistory.loadHistory();
                if($.NavTabHistory&&data){
                    for(var i=0;i<data.length;i++){
                        var option=this.convertToOption(data[i]);
                        if(option){
                            top.indexFrame.frames['mainframe'].show_tab(option);
                        }
                        this.navTabIds.push(option.tabId);//用来维护页面范围的一个tabid
                    }
                }
                $.NavTabHistory.navtabSaveFlag=true;
            },
            navTabKey:'mams-#iqiyi',
            navTabMax:1, //保存最后打开的tab数目
            navTabSplitStr:'%#%',
            navDataSplitStr:'!*!',
            navTabIds:new Array(),
            navtabSaveFlag:true,
			historyCheck: function(){
                var history=jQuery.cookie(this.navTabKey);
                return history&&history.length>0;
			},
			addHistory: function(data){
                var history=jQuery.cookie(this.navTabKey);
                var dataArray=null;
                if(!history||history.length<=0){
                    dataArray=new Array(this.convertToString(data));
                    this.navTabIds.push(data.tabId+"");
                }else{
                    dataArray=history.split(this.navTabSplitStr);
                    if(dataArray.length>=this.navTabMax){
                        var tmpData=dataArray.shift();
                        var tmpOption=this.convertToOption(tmpData);
                        this.navTabIds.splice(this.isSaved(tmpOption.navTabId),1);
                    }
                    this.navTabIds.push(data.tabId+"");
                    dataArray.push(this.convertToString(data));
                }
                jQuery.cookie(this.navTabKey,dataArray.join(this.navTabSplitStr),{expires: 7});
            },
            _getHistoryIndex:function(data,tabId){
                if(!data)return -1;
                for(var i=0,l=data.length;i<l;i++){
                    var option=this.convertToOption(data[i]);
                    if(option&&option.tabId==tabId){
                        return i;
                    }
                }
                return -1;
            },
			loadHistory: function(){
                var history=jQuery.cookie(this.navTabKey);
                var dataArray=null;
                if(history){
                    dataArray=history.split(this.navTabSplitStr);
                }
                return dataArray;
            },
            addFlag: function(key,value){
                jQuery.cookie(this.navTabKey+"key",value);
            },
            isSaved:function(navId){
                if(!navId)return -1;
                for(var i=0,l=this.navTabIds.length;i<l;i++){
                    if(navId==this.navTabIds[i].toString()){
                        return i;
                    }
                }
                return -1;
            },
            clearHistory:function(){
                this.navTabIds=new Array();
                jQuery.cookie(this.navTabKey,null);
            },
            convertToString:function(data){
                if(data){
                    return data.tabId+this.navDataSplitStr+data.title+this.navDataSplitStr+data.url+this.navDataSplitStr+(data.fresh?"1":"")+this.navDataSplitStr+(data.external?"1":"")+this.navDataSplitStr+(data.reloadFlag?"1":"")+this.navDataSplitStr+data.extend;
                }
                return "";
            },
            convertToOption:function(data){
                var option=null;
                if(data){
                    var array=data.split(this.navDataSplitStr);
                    if(array&&array.length>=5){
                        option={tabId:array[0],title:array[1],url:array[2],fresh:Boolean(array[3]),external:Boolean(array[4]),reloadFlag:Boolean(array[5]),extend:array[6]};
                    }
                }
                return option;
            },
            setcookie: function(cookieName, cookieValue, seconds, path, domain, secure) {
                var expires = new Date();
                expires.setTime(expires.getTime() + seconds);
                document.cookie = escape(cookieName) + '=' + escape(cookieValue)
                    + (expires ? '; expires=' + expires.toGMTString() : '')
                    + (path ? '; path=' + path : '/')
                    + (domain ? '; domain=' + domain : '')
                    + (secure ? '; secure' : '');
            }
        }
	});
})(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '/';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        var str=[name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        document.cookie=str;

    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
function clearCookie(){
    if($.NavTabHistory){
        $.NavTabHistory.clearHistory();
    }
}